import  { constantRoutes } from '@/router'
// import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView';
import store from "@/store";
import { getMenusApi } from '@/api/idaas'
import { MessageBox  } from 'element-ui'
import { findTreeNode } from "@/utils/tree";

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes.concat();
    },
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = routers
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise((resolve, reject) => {
        // 向后端请求路由数据
        getMenusApi().then((res) => {
          // res = MOCKDATA
          if (res?.code !== 200) {
            return
          }
          if (res?.data?.length) {
            const sdata = JSON.parse(JSON.stringify(res.data))
            const sidebarRoutes = filterAsyncRouter(sdata)
            const rdata = fixRouter(JSON.parse(JSON.stringify(res.data)))
            const rewriteRoutes = filterAsyncRouter(rdata, true)
            rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })

            commit('SET_ROUTES', rewriteRoutes)
            // commit('SET_SIDEBAR_ROUTERS', sidebarRoutes)
            commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
            commit('SET_DEFAULT_ROUTES', sidebarRoutes)
            commit('SET_TOPBAR_ROUTES', sidebarRoutes)
            resolve(rewriteRoutes)
          } else {
            MessageBox.alert('当前用户没有菜单权限！', '提示', {
              confirmButtonText: '确定',
              callback: () => {

              },
            })
            reject()
          }
        })
      })
    }
  }
}

function fixRouter(routers){
  let result = []
  routers.forEach(ele=>{
    if(ele.component&&!['Layout','ParentView'].includes(ele.component)){
      const p = {
        alwaysShow:true,
        children:[ele],
        component:'Layout',
        hidden:false,
        meta: {title:ele.meta.title,icon:'',noCache:false},
        name:`Layout${ele.name}`,
        path:`/layout${ele.name}`,
        redirect:'noRedirect'
      }
      result.push(p)
    } else {
      result.push(ele)
    }
  })
  return result
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, isRewrite = false) {
  return asyncRouterMap.filter(route => {
    route.meta.noCache = false

    if (isRewrite && route.children) {
      route.children = filterChildren(route.children)
    }

    if (route.component) {
      // pad端的特殊处理
      if (["mobile", "pad"].includes(store.state.app.device)) {
        const chilRouter = findTreeNode([route], node => /@pad$/.test(node.component))
        if (chilRouter && /@pad$/.test(chilRouter.component)) {
          route.hidden = false
        } else {
          route.hidden = true
        }
      }
      if (/@pad$/.test(route.component)) {
        route.component = route.component.slice(0,route.component.length-4)
      }

      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (typeof route.component === 'string') {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, isRewrite)
    }
    return true
  })
}
function filterChildren(childrenMap) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => { // 路由懒加载
  // console.log(view)
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
